<?php

$unique_token = "1459142648167";

if (isset($_GET['id']) && isset($_GET['mname']) && isset($_GET['pid'])) {
	
	mysql_connect("localhost", "root", "") or die(mysql_error());
	mysql_select_db("elections") or die(mysql_error());

	$id = mysql_real_escape_string($_GET['id']);
	$pid = mysql_real_escape_string($_GET['pid']);
	$mname = mysql_real_escape_string($_GET['mname']);

	$result = mysql_query("SELECT * FROM voters WHERE id='$id' AND (fid='$pid' OR mid='$pid') AND mname='$mname' AND voted=0")
	or die(mysql_error());  
	
	$num_rows = mysql_num_rows($result);
	if ($num_rows ==1) {
	
		$row = mysql_fetch_array($result);	
		$committee_no = $row['committee_no'];
		$index_no = $row['index_no'];
		$token = md5($row['id'].$row['committee_no'].$row['index_no'].$unique_token);
		
		if ($row['token']==0){
			mysql_query("INSERT INTO tokens (token, index_no, committee_no,date) VALUES ('$token','$index_no','$committee_no',NOW())");
			mysql_query("UPDATE voters SET token=1 WHERE id='$id'");
			echo json_encode(array('token' => $token));
		} else {
			echo json_encode(array('token' => $token));
		}
		
		
	} else {
		echo json_encode(array('error' => 'not a valid voter'));
	}
	
} else { 
	echo json_encode(array('error' => 'id or mother\'s name was not provided'));
}
?>